package org.jinghouyu.json.utils;

import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Set;

public class IdentitySet<E> implements Set<E> {

	private IdentityHashMap<E, String> map = null;
	private final static String value = "";

	public IdentitySet(int size) {
		map = new IdentityHashMap<E, String>(size);
	}

	public IdentitySet() {
		this(20);
	}

	@Override
	public int size() {
		return map.size();
	}

	@Override
	public boolean isEmpty() {
		return map.size() == 0;
	}

	@Override
	public boolean contains(Object o) {
		return map.containsKey(o);
	}

	@Override
	public Iterator<E> iterator() {
		return map.keySet().iterator();
	}

	@Override
	public Object[] toArray() {
		return map.keySet().toArray();
	}

	@Override
	public <T> T[] toArray(T[] a) {
		return map.keySet().toArray(a);
	}

	@Override
	public boolean add(E e) {
		return map.put(e, "") == null;
	}

	@Override
	public boolean remove(Object o) {
		return map.remove(o) != null;
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		return map.keySet().containsAll(c);
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		for (E e : c) {
			map.put(e, value);
		}
		return true;
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		return map.keySet().retainAll(c);
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		return map.keySet().removeAll(c);
	}

	@Override
	public void clear() {
		map.clear();
	}

}
